package com.papers.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.papers.common.annotation.Log;
import com.papers.common.annotation.RepeatSubmit;
import com.papers.common.core.controller.BaseController;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.domain.entity.SysUser;
import com.papers.common.core.page.TableDataInfo;
import com.papers.common.core.validate.AddGroup;
import com.papers.common.core.validate.EditGroup;
import com.papers.common.enums.BusinessType;
import com.papers.common.excel.ExcelResult;
import com.papers.common.utils.poi.ExcelUtil;
import com.papers.system.domain.bo.TJuanCourseBo;
import com.papers.system.domain.dto.MergeCourseDto;
import com.papers.system.domain.dto.TJuanCourseDto;
import com.papers.system.domain.dto.TJuanUserCourseDto;
import com.papers.system.domain.vo.TJuanCourseListVo;
import com.papers.system.domain.vo.TJuanCourseVo;
import com.papers.system.domain.vo.TJuanMajorTreeVo;
import com.papers.system.service.ITJuanCourseService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * 课程
 *
 * @author papers
 * @date 2022-10-12
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/juanCourse")
public class TJuanCourseController extends BaseController {

    private final ITJuanCourseService iTJuanCourseService;

    /**
     * 查询课程列表
     */
    @SaCheckPermission("system:juanCourse:list")
    @GetMapping("/list")
    public TableDataInfo<TJuanCourseVo> list(TJuanCourseDto dto, PageQuery pageQuery) {
        return iTJuanCourseService.queryPageList(dto, pageQuery);
    }

    /**
     * 导入课程列表
     */
    @SaCheckPermission("system:juanCourse:import")
    @Log(title = "课程", businessType = BusinessType.IMPORT)
    @PostMapping("/importFile")
    public void importFile(@RequestPart("file") MultipartFile file) {
        InputStream fis = null;
        try {
            fis = file.getInputStream();
            ExcelResult<TJuanCourseListVo> result = ExcelUtil.importExcel(fis, TJuanCourseListVo.class, true);
            List<TJuanCourseListVo> list = result.getList();
            iTJuanCourseService.save(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    /**
     * 导出课程列表
     */
    @SaCheckPermission("system:juanCourse:export")
    @Log(title = "课程", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TJuanCourseBo bo, HttpServletResponse response) {
        List<TJuanCourseListVo> list = iTJuanCourseService.queryList(bo);
        ExcelUtil.exportExcel(list, "课程", TJuanCourseListVo.class, response);
    }

    /**
     * 获取课程详细信息
     *
     * @param courseId 主键
     */
    @SaCheckPermission("system:juanCourse:query")
    @GetMapping("/{courseId}")
    public R<TJuanCourseVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String courseId) {
        return R.ok(iTJuanCourseService.queryById(courseId));
    }

    /**
     * 新增课程
     */
    @SaCheckPermission("system:juanCourse:add")
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TJuanCourseBo bo) {
//        int i = iTJuanCourseService.CourseCodeUnique(bo);
//        if (i==0){
//            return R.fail("新增课程失败，课程编号"+bo.getCourseCode()+"已存在");
//        }
        return toAjax(iTJuanCourseService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改课程
     */
    @SaCheckPermission("system:juanCourse:edit")
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TJuanCourseBo bo) {
//        int i = iTJuanCourseService.CourseCodeUnique(bo);
//        if (i==0){
//            return R.fail("修改课程失败，课程编号"+bo.getCourseCode()+"已存在");
//        }
        return toAjax(iTJuanCourseService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除课程
     *
     * @param courseIds 主键串
     */
    @SaCheckPermission("system:juanCourse:remove")
    @Log(title = "课程", businessType = BusinessType.DELETE)
    @DeleteMapping("/{courseIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] courseIds) {
        return toAjax(iTJuanCourseService.deleteWithValidByIds(Arrays.asList(courseIds), true) ? 1 : 0);
    }

    /**
     * 根据专业id查询课程列表
     * @return
     */
    @GetMapping("/getCourseByMajorId")
    public R getCourseByMajorId() {
        return iTJuanCourseService.getCourseByMajorId();
    }

    /**
     * 查询专业树
     *
     * @return
     */
    @GetMapping("/getMajorTree")
    public R<List<TJuanMajorTreeVo>> getMajorTree() {
        List<TJuanMajorTreeVo> majorTreeList = iTJuanCourseService.getMajorTreeList();
        return R.ok(majorTreeList);
    }

    /**
     * 查询已绑定课程的用户
     * @param dto
     * @param pageQuery
     * @return
     */
    @GetMapping("/bindUser/allocatedList")
    public TableDataInfo<SysUser> allocatedList(TJuanUserCourseDto dto, PageQuery pageQuery) {
        return iTJuanCourseService.selectAllocatedList( pageQuery,dto);
    }

    /**
     * 查询未绑定课程的用户
     * @param dto
     * @param pageQuery
     * @return
     */
    @GetMapping("/bindUser/unallocatedList")
    public TableDataInfo<SysUser> unallocatedList(TJuanUserCourseDto dto, PageQuery pageQuery) {
        return iTJuanCourseService.selectUnallocatedList(pageQuery, dto);
    }

    /**
     * 批量取消授权用户
     * @param courseId
     * @param userIds
     * @return
     */
    @PutMapping("/bindUser/cancelAll")
    public void cancelBindUserAll(@RequestParam("courseId") String courseId,@RequestParam("userIds") String[] userIds) {
        iTJuanCourseService.deleteBindUsers(courseId,userIds);
    }

    /**
     * 批量选择用户授权
     * @param courseId
     * @param userIds
     * @return
     */
    @PutMapping("/bindUser/selectAll")
    public R selectBindUserAll(@RequestParam("courseId") String courseId,@RequestParam("userIds") String[] userIds) {
        return R.ok(iTJuanCourseService.insertBindUsers(courseId,userIds));
    }

    @GetMapping("/getTreeAndCourse")
    public R getTreeAndCourse() {
        return iTJuanCourseService.getTreeAndCourse();
    }

    /**
     * 题库汇总统计
     */
    @GetMapping("/total")
    public R tikuTotal() {
        return R.ok(iTJuanCourseService.tikuTotal());
    }

    /**
     * 题库-汇总统计
     *
     * @return
     */
    @GetMapping("/getStatisticsByTotal")
    public R getStatisticsByTotal(TJuanCourseDto dto) {
        return R.ok(iTJuanCourseService.getStatisticsByTotal(dto));
    }

    @PostMapping("/mergeCourse")
    public R mergeCourse(@RequestBody MergeCourseDto mergeCourseDto) {
        return iTJuanCourseService.mergeCourse(mergeCourseDto.getMainId(), mergeCourseDto.getIds());
    }

    /**
     * 查看题库编码
     * @param bo
     * @return
     */
    @GetMapping("/check")
    public String checkCourseCode(TJuanCourseBo bo) {
        return iTJuanCourseService.checkCourseCode(bo);
    }
}
